// 请求日志中间件
function logger(req, res, next) {
  const start = Date.now();
  
  // 获取请求的基本信息
  const { method, url, headers, body, query, params } = req;
  const ip = req.ip || req.connection.remoteAddress;
  
  // 记录请求开始
  console.log(`[${new Date().toISOString()}] ${method} ${url} from ${ip}`);
  
  // 如果是开发环境，显示更详细的请求信息
  if (process.env.NODE_ENV === 'development') {
    // 只记录非敏感信息和合理大小的请求体
    const safeBody = {};
    for (const key in body) {
      // 排除敏感信息
      if (!['password', 'token', 'apiKey'].includes(key.toLowerCase())) {
        // 限制字符串长度，避免大请求体日志
        if (typeof body[key] === 'string' && body[key].length > 1000) {
          safeBody[key] = body[key].substring(0, 1000) + '... (truncated)';
        } else {
          safeBody[key] = body[key];
        }
      }
    }
    
    if (Object.keys(safeBody).length > 0) {
      console.log('Request Body:', safeBody);
    }
    
    if (Object.keys(query).length > 0) {
      console.log('Request Query:', query);
    }
  }
  
  // 监听响应完成事件，记录响应时间和状态码
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`[${new Date().toISOString()}] ${method} ${url} ${res.statusCode} ${duration}ms`);
  });
  
  next();
}

module.exports = logger;